/**
 * 线段是否相交
 * seg: [{ lat: xxx, lng: xxx }, { lat: xxx, lng: xxx }]
 * */
export function isSegmentsIntersectant(segA, segB) {
  const abc = (segA[0].lat - segB[0].lat) * (segA[1].lng - segB[0].lng) - (segA[0].lng - segB[0].lng) * (segA[1].lat - segB[0].lat)
  const abd = (segA[0].lat - segB[1].lat) * (segA[1].lng - segB[1].lng) - (segA[0].lng - segB[1].lng) * (segA[1].lat - segB[1].lat)
  if (abc * abd >= 0) {
    return false
  }

  const cda = (segB[0].lat - segA[0].lat) * (segB[1].lng - segA[0].lng) - (segB[0].lng - segA[0].lng) * (segB[1].lat - segA[0].lat)
  const cdb = cda + abc - abd
  return !(cda * cdb >= 0)
}

/**
 *  判断多边形是否自相交
 *  */
export function isPolygonSelfIntersectant(ply) {
  for (let i = 0; i < ply.length; i++) {
    const index = (num) => num >= ply.length ? num % ply.length : num
    const segA = [ply[i], ply[index(i + 1)]]
    const segB = [ply[index(i + 2)], ply[index(i + 3)]]
    if (isSegmentsIntersectant(segA, segB)) {
      return true
    }
  }
  return false
}

/**
 * 判断两多边形是否相交
 */
export function isPolygonsOverlap(plyA, plyB) {
  for (let i = 0, il = plyA.length; i < il; i++) {
    for (let j = 0, jl = plyB.length; j < jl; j++) {
      const segA = [plyA[i], plyA[i === il - 1 ? 0 : i + 1]]
      const segB = [plyB[j], plyB[j === jl - 1 ? 0 : j + 1]]
      if (isSegmentsIntersectant(segA, segB)) {
        return true
      }
    }
  }
  return false
}
